/**
 * 
 */

package com.liferay.opensourceforlife.events;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.liferay.portal.kernel.events.Action;
import com.liferay.portal.kernel.events.ActionException;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.struts.LastPath;
import com.liferay.portal.kernel.util.PrefsPropsUtil;
import com.liferay.portal.kernel.util.PropsKeys;
import com.liferay.portal.kernel.util.StringPool;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.portal.kernel.util.WebKeys;
import com.liferay.portal.model.Group;
import com.liferay.portal.model.Organization;
import com.liferay.portal.model.User;
import com.liferay.portal.service.GroupLocalServiceUtil;
import com.liferay.portal.util.PortalUtil;

/**
 * @author Tejas Kanani
 */
public class CustomLandingPageAction extends Action {

	@Override
	public void run(HttpServletRequest request, HttpServletResponse response)
		throws ActionException {

		try {
			doRun(request, response);
		}
		catch (Exception e) {
			throw new ActionException(e);
		}
	}

	protected void doRun(
		HttpServletRequest request, HttpServletResponse response)
		throws Exception {

		long companyId = PortalUtil.getCompanyId(request);

		String path =
			PrefsPropsUtil.getString(
				companyId, PropsKeys.DEFAULT_LANDING_PAGE_PATH);

		if (_log.isInfoEnabled()) {
			_log.info(PropsKeys.DEFAULT_LANDING_PAGE_PATH + StringPool.EQUAL +
				path);
		}

		if (Validator.isNull(path)) {
			path = getCustomLandingPage(request);
		}

		HttpSession session = request.getSession();
		session.setAttribute(WebKeys.LAST_PATH, new LastPath(
			StringPool.BLANK, path));

	}

	/**
	 * Returns custom landing page path after user login
	 * 
	 * @param request
	 * @return
	 * @throws PortalException
	 * @throws SystemException
	 */
	private String getCustomLandingPage(HttpServletRequest request)
		throws PortalException, SystemException {

		String customLandingPagePath = StringPool.BLANK;

		/*
		 * For getting landing path for Organization
		 */
		// customLandingPagePath =
		// getOrganizationPath(PortalUtil.getUser(request), false);

		/*
		 * For getting landing path for Site
		 */
		customLandingPagePath = getSitePath(PortalUtil.getUser(request), false);

		return customLandingPagePath;
	}

	/**
	 * Returns custom landing path for organization which user belongs to.
	 * 
	 * @param user
	 * @param includeLanguage
	 * @return
	 * @throws PortalException
	 * @throws SystemException
	 */
	private String getOrganizationPath(User user, boolean includeLanguage)
		throws PortalException, SystemException {

		String organizationPath = StringPool.BLANK;
		List<Organization> userOrganizations = user.getOrganizations();
		String language = StringPool.BLANK;

		if (includeLanguage) {
			language = StringPool.SLASH + user.getLocale().getLanguage();
		}

		if ((userOrganizations != null) && !userOrganizations.isEmpty()) {
			String organizationFriendlyURL =
				userOrganizations.get(0).getGroup().getFriendlyURL();
			organizationPath = language + "/web" + organizationFriendlyURL;
		}

		return organizationPath;
	}

	/**
	 * Returns custom landing path for <code>Site</code> which user belongs to.
	 * 
	 * @param user
	 * @param includeLanguage
	 * @return
	 * @throws PortalException
	 * @throws SystemException
	 */
	private String getSitePath(User user, boolean includeLanguage)
		throws PortalException, SystemException {

		String sitePath = StringPool.BLANK;
		List<Group> userSites = getSites(user.getUserId());

		String language = StringPool.BLANK;

		if (includeLanguage) {
			language = StringPool.SLASH + user.getLocale().getLanguage();
		}

		if ((userSites != null) && !userSites.isEmpty()) {
			String siteFriendlyURL = userSites.get(0).getFriendlyURL();
			sitePath = language + "/web" + siteFriendlyURL;
		}

		return sitePath;
	}

	/**
	 * Returns all the <code>Sites</code> which user belongs to, other than
	 * Guest
	 * 
	 * @param userId
	 * @return
	 * @throws PortalException
	 * @throws SystemException
	 */
	private List<Group> getSites(long userId)
		throws PortalException, SystemException {

		List<Group> sites = new ArrayList<Group>();

		for (Group group : GroupLocalServiceUtil.getUserGroups(userId)) {
			if (group.isRegularSite() &&
				!"Guest".equalsIgnoreCase(group.getName())) {
				sites.add(group);
				break;
			}
		}
		return sites;
	}

	private static Log _log =
		LogFactoryUtil.getLog(CustomLandingPageAction.class);
}
